package org.ligson.springboot.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class RedisUtils {

    public static List<String> deleteKeys(RedisTemplate redisTemplate, String keyPattern) {
        List<String> keys = scanKeys(redisTemplate, keyPattern);
        redisTemplate.delete(keys);
        return keys;
    }

    public static List<String> scanKeys(RedisTemplate redisTemplate, String pattern) {
        return scanKeys(redisTemplate, -1, pattern);
    }

    @SuppressWarnings("unchecked")
    public static List<String> scanKeys(RedisTemplate redisTemplate, int count, String pattern) {
        long countValue = count > 0 ? count : Integer.MAX_VALUE;
        return (List<String>) redisTemplate.execute((RedisCallback<List<String>>) connection -> {
            List<String> keys1 = new ArrayList<>();
            ScanOptions so = ScanOptions.scanOptions().count(countValue).match(pattern).build();
            try (Cursor<byte[]> cur = connection.scan(so)) {
                long pos = cur.getPosition();
                while ((!cur.isClosed()) && cur.hasNext()) {
                    byte[] key = cur.next();
                    keys1.add(new String(key, StandardCharsets.UTF_8));
                }
            } catch (IOException e) {
                ///log.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }
            return keys1;
        });
    }
}
